﻿using System;
using Microsoft.Win32;

namespace TeamDeploy.Tasks.Tests
{
    class Utility
    {
        public static bool IsInstalled(string uninstallProductName, string targetMachine)
        {
            RegistryKey regKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, targetMachine);
            RegistryKey tempKey;

            uninstallProductName = uninstallProductName.Trim().ToLower();

            regKey = regKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false);

            foreach (string subKey in regKey.GetSubKeyNames())
            {
                tempKey = regKey.OpenSubKey(subKey, false);

                if (Array.IndexOf(tempKey.GetValueNames(), "DisplayName") >= 0)
                {
                    if (tempKey.GetValue("DisplayName").ToString().ToLower()
                        .StartsWith(uninstallProductName))
                    {
                        return true;
                    }
                }
            }

            // no match
            return false;
        }
    }
}
